<template>
  <div class="view-fill">
    <div
      v-show="!assetDetailInfo.visible && !receivingDetailInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-deptName>
                <el-input
                  v-model="formInfo.data.deptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <div class="filter-wrapper">
              <page-filter :filter-list="filterInfo.list">
                <template v-slot:filter-addProduct>
                  <el-button
                    :disabled="!formInfo.data.deptId"
                    @click="addProduct"
                    >添加资产
                  </el-button>
                </template>

                <template v-slot:filter-removeProduct>
                  <el-button
                    :disabled="!canRemoveProduct"
                    @click="removeProduct()"
                    >删除资产
                  </el-button>
                </template>
              </page-filter>
              <div class="display-flex">
                <el-button
                  style="margin-left: 10px"
                  :disabled="!tableInfo.data.length"
                  @click="changeNumberAll(true)"
                  >一键验收
                </el-button>
                <el-button
                  style="margin-left: 10px"
                  :disabled="!tableInfo.data.length"
                  @click="changeNumberAll(false)"
                  >一键清空
                </el-button>
              </div>
            </div>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="false"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                      >{{ scope.row.assetName }}</span
                    >
                  </template>
                  <template v-slot:col-receivingOrderNo="scope">
                    <span
                      class="slip-edit"
                      @click="showReceivingDetail(scope.row)"
                      >{{ scope.row.receivingOrderNo }}</span
                    >
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!--部门选择框-->
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDeptInfo.query"
      :save-empty="true"
      @callback="selectDeptCallback"
    />
    <asset-receiving-detail
      v-if="receivingDetailInfo.visible"
      :id="receivingDetailInfo.id"
      :source-type="receivingDetailInfo.receiveOrderSourceType"
      v-model:visible="receivingDetailInfo.visible"
      @returnBack="getList"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
    <editAcceptance
      v-if="acceptanceDetailsInfo.visible"
      v-model:show-dialog="acceptanceDetailsInfo.visible"
      :info="acceptanceDetailsInfo.info"
      @callback="callbackEditAcceptance"
    />
    <SelectAsset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      @callback="callbackAsset"
    />
  </div>
</template>
<script setup>
import { getCustomizeSetting } from '@/api/customize'
import {
  createAcceptance,
  updateAcceptance,
  getAcceptanceById,
  getAcceptanceDetailsAll,
} from '@/api/asset'
import SelectAsset from './addAsset'
import editAcceptance from './editAcceptance'
import AssetReceivingDetail from '@/views/asset/assetManage/assetReceiving/details'
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formInfo = ref({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
  },
  fieldList: [
    {
      label: '验收部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '验收结论',
      value: 'acceptanceConclusion',
      type: 'textarea',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    deptName: [
      {
        required: true,
        message: '请选择验收部门',
        trigger: 'change',
      },
    ],
    acceptanceConclusion: [
      {
        required: true,
        message: '请输入验收结论',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {
      withDetails: true,
    },
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'removeProduct',
    },
  ],
})
const tableInfo = ref({
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '验收详情',
        event: acceptanceDetail,
        show: true,
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
    useDeptId: '',
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      acceptanceFlag: true,
      detailStatusMult: '2,3',
      assetAcceptanceOrderId: props.id,
      // deleteReceivingDetailIdsMult: null,
    },
  },
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const receivingDetailInfo = ref({
  visible: false,
  receiveOrderSourceType: '',
  id: '',
})
const acceptanceDetailsInfo = ref({
  visible: false,
  info: {},
})
const formRefs = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

setData()
function setData() {
  let obj = {
    receivingOrderNo: {
      label: '收货单号',
      value: 'receivingOrderNo',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    purchTypeValue: {
      label: '采购类型',
      value: 'purchTypeValue',
      asValue: 'purchType',
      componentType: 'select-model',
      type: 'select-model',
      code: 'asset_purch_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function changeNumberAll(type) {
  if (type) {
    tableInfo.value.data.forEach((item) => {
      if (item.details && item.details.length) {
        let details = proxy.$fn.deepClone(item.details)
        let index = details.findIndex(
          (item) =>
            item.instructions == '1' &&
            item.certificate == '1' &&
            item.warrantyCard == '1' &&
            item.buinessInspectOrder == '1' &&
            item.inspectionReport == '1'
        )
        if (index > -1) {
          let data = proxy.$fn.deepClone(details[index])
          let sumQty = 0
          details.forEach((item) => {
            sumQty = proxy.$fn.accAdd(item.qty || 0, sumQty)
          })
          sumQty = proxy.$fn.Subtr(sumQty, data.qty)
          let qty = proxy.$fn.Subtr(item.pendAcceptanceQty || 0, sumQty)
          item.details[index].qty = qty
          item.details[index].calcQty = qty
          item.qty = item.pendAcceptanceQty
          item.calcQty = item.pendAcceptanceQty
        } else {
          let data = proxy.$fn.deepClone(details[0])
          data.instructionsValue = '有'
          data.instructions = '1'
          data.certificateValue = '有'
          data.certificate = '1'
          data.warrantyCardValue = '有'
          data.warrantyCard = '1'
          data.buinessInspectOrderValue = '有'
          data.buinessInspectOrder = '1'
          data.inspectionReportValue = '有'
          data.inspectionReport = '1'
          let sumQty = 0
          details.forEach((item) => {
            sumQty = proxy.$fn.accAdd(item.qty || 0, sumQty)
          })
          let qty = proxy.$fn.Subtr(item.pendAcceptanceQty || 0, sumQty)
          data.qty = qty
          data.calcQty = qty
          item.details.unshift(data)
          item.qty = item.pendAcceptanceQty
          item.calcQty = item.pendAcceptanceQty
        }
      } else {
        let data = proxy.$fn.deepClone(item)
        data.qty = data.pendAcceptanceQty
        data.calcQty = data.pendAcceptanceQty
        data.instructionsValue = '有'
        data.instructions = '1'
        data.certificateValue = '有'
        data.certificate = '1'
        data.warrantyCardValue = '有'
        data.warrantyCard = '1'
        data.buinessInspectOrderValue = '有'
        data.buinessInspectOrder = '1'
        data.inspectionReportValue = '有'
        data.inspectionReport = '1'
        item.details = [data]
        item.qty = data.qty
        item.calcQty = data.calcQty
      }
    })
  } else {
    tableInfo.value.data.forEach((item) => {
      item.qty = 0
      if (item.details && item.details.length) {
        item.details = []
      }
    })
  }
}
function acceptanceDetail(row) {
  if (row.details && row.details.length) {
    acceptanceDetailsInfo.value.info = row
  } else {
    let details = proxy.$fn.deepClone(row)
    let data = proxy.$fn.deepClone(row)
    if (details.details) {
      delete details.details
    }
    details.qty = 0
    details.calcQty = 0
    details.instructionsValue = '有'
    details.instructions = '1'
    details.certificateValue = '有'
    details.certificate = '1'
    details.warrantyCardValue = '有'
    details.warrantyCard = '1'
    details.buinessInspectOrderValue = '有'
    details.buinessInspectOrder = '1'
    details.inspectionReportValue = '有'
    details.inspectionReport = '1'
    data.details = [details]
    acceptanceDetailsInfo.value.info = data
  }
  console.log(acceptanceDetailsInfo.value)
  acceptanceDetailsInfo.value.visible = true
}
function callbackEditAcceptance(data) {
  let index = tableInfo.value.data.findIndex((item) => item.id === data.id)
  console.log(index)
  if (index > -1) {
    tableInfo.value.data[index] = data
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.id ? updateAcceptance : createAcceptance
    let mergeDetails = tableInfo.value.data.filter((item) => item.qty > 0)
    if (!mergeDetails.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请验收资产！',
      })
      return
    }
    let data = formInfo.value.data
    data.mergeDetails = mergeDetails
    api(data).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
function selectDeptCallback(row) {
  if (row && row.id) {
    formInfo.value.data['deptName'] = row.name
    formInfo.value.data['deptId'] = row.id
  } else {
    formInfo.value.data['deptName'] = ''
    formInfo.value.data['deptId'] = ''
  }
}
function addProduct() {
  let ids = ''
  if (tableInfo.value.data.length) {
    ids = tableInfo.value.data.map((item) => item.receivingDetailId).toString()
  }
  selectAssetInfo.value.query.queryMap.id.value = ids
  selectAssetInfo.value.visible = true
}
function callbackAsset(data) {
  if (data && data.length) {
    data.forEach((item) => {
      item.qty = 0
      item.calcQty = 0
      item.receivingDetailId = item.id
      item.receivingOrderId = item.orderId
      item.receivingOrderNo = item.orderNo
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.id) {
    if (props.id) {
      selectAssetInfo.value.query.queryParams.deleteReceivingDetailIdsMult =
        String(selectRow.receivingDetailId)
    }
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        if (props.id) {
          selectAssetInfo.value.query.queryParams.deleteReceivingDetailIdsMult =
            tableInfo.value.selections
              .map((item) => item.receivingDetailId)
              .toString()
        }
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function showReceivingDetail(row) {
  receivingDetailInfo.value.id = row.receivingOrderId
  receivingDetailInfo.value.receiveOrderSourceType = row.receiveOrderSourceType
  receivingDetailInfo.value.visible = true
}
function getMain() {
  getAcceptanceById(props.id).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
    }
  })
}
function getList() {
  getAcceptanceDetailsAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetAcceptanceOrderModify-com.slip.spd.entity.vo.asset.AssetAcceptanceOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      if (props.id) {
        getMain()
        getList()
      }
    }
  })
}
</script>
